<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\model\Message;
use plugin\admin\app\model\User;
use support\Request;
use support\Response;
use plugin\admin\app\model\MessageChat;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 客服会话 
 */
class MessageChatController extends Crud
{
    
    /**
     * @var MessageChat
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new MessageChat;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('message-chat/index');
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('message-chat/insert');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }
        return view('message-chat/update');
    }

    protected function formatNormal($items, $total): Response
    {
        $userIds = array_column($items, 'user_id');
        $users = User::whereIn('id', $userIds)->get()->toArray();
        $users = array_combine(
            array_column($users, 'id'),
            array_values($users)
        );

        foreach ($items as $key=>$item) {
            $items[$key]['user_info'] = $users[$item['user_id']];
            $items[$key]['last_message_type'] = Message::getMessageTypeText($item['last_message_type']);
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

}
